﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using BulkCSVImporter;
using Microsoft.SharePoint.Taxonomy;
using Microsoft.SharePoint;

namespace BulkCVSImporter
{
    public partial class MMS : Form
    {
        public object ManagedStore { get { return lsbStores.SelectedIndex == -1 ? "" : lsbStores.SelectedItem; } }
        public string StoreUrl { get; set; }

        List<MetaStoreHolder> mms = new List<MetaStoreHolder>();

        public MMS()
        {
            InitializeComponent();
        }

        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {

            
            string socialDataStatsSite = StoreUrl;
            TermStoreCollection _store = null;
            TaxonomySession _session = null;

            //Obtain current site
            using (SPSite siteColl = new SPSite(socialDataStatsSite))
            {
                //Get The context object that encapsulates all information required to make a call to a service application.
                SPServiceContext serviceContext = SPServiceContext.GetContext(siteColl);

                //The entry point to accessing all data associated with TermStore objects and performing searches across them.
                _session = new TaxonomySession(siteColl);

                //Represents a "term store" database.
                _store = _session.TermStores;


                foreach (TermStore item in _store)
                {
                    MetaStoreHolder holder = new MetaStoreHolder();
                    holder.Guid = item.Id;
                    holder.Title = item.Name;
                    mms.Add(holder);
                }
            }
        }

        private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            foreach (MetaStoreHolder item in mms)
            {
                lsbStores.Items.Add(item);
            }

            btnGetStores.Enabled = true;
        }

        private void btnGetStores_Click(object sender, EventArgs e)
        {
            btnGetStores.Enabled = false;
            lsbStores.Items.Clear();
            backgroundWorker1.RunWorkerAsync();
        }
    }

    class MetaStoreHolder
    {
        public string Title { get; set; }
        public Guid Guid { get; set; }

        public override string ToString()
        {
            return Title;
        }
    }
}
